<?php


function json($success, $message = "", $data = array())
{
  $result = array(
    'success' => $success,
    'message' => urlencode($message),
    'docs' => $data
  );  
  //输出json  
  echo urldecode(json_encode($result));
}

$servername = "localhost";
$username = "root";
$password = "";
$dbName = 'taodb';
$tbnameA = 'project_fatherclass';
$tbnameB = "project_childrenclass";

$mysqli = new mysqli($servername, $username, $password, $dbName);

if ($mysqli->connect_error) {
  die("连接失败: " . $mysqli->connect_error);
}


$sql = "SELECT a.name,a.id,b.childrenname,b._id FROM $tbnameA a RIGHT JOIN $tbnameB b ON a.childrenid = b.fatherid ORDER BY a.name";
$result = $mysqli->query($sql);
$data = array();
if ($result) {

  $temp = '';
  $row = $result->fetch_assoc();
  for ($j = 0; ; $j++) {
    $temp = $row['name'];
    for ($i = 0;$temp === $row['name']; $i++) {  
      $data[$j]['id'] = $row['id'];
      $data[$j]['name'] = $row['name'];
      $data[$j]['children'][$i]['id'] = $row['_id'];
      $data[$j]['children'][$i]['name'] = urlencode($row['childrenname']);
      $row = $result->fetch_assoc();
      // $row = $result->fetch_assoc();
    }
    if ($row === null) {
      break;
    }
  }
  json('true', '查询成功', $data);
} else {
  json('false', '查询失败', $data);
}

